package com.qq.server.model;

import com.qq.common.Message;
import com.qq.common.MessageType;
import com.qq.common.User;
import com.qq.server.dao.UserDao;
import com.qq.server.dao.UserDaoImpl;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author weiBin
 * @date 2019/1/9
 */
public class MyQqServer {
    private static ServerSocket serverSocket = null;
    private static Thread thread = null;

    private MyQqServer() {

    }

    public static void start() {
        synchronized (MyQqServer.class) {
            if (thread == null) {
                thread = new Thread(() -> {
                    run();
                });
                thread.start();
            }
        }
    }

    private static void run() {
        try {
            serverSocket = new ServerSocket(8888);
            System.out.println("服务器开始监听8888端口");
            while (true) {
                Socket socket = serverSocket.accept();
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                User user = (User) ois.readObject();
                Message message = new Message();
                UserDao userDao = new UserDaoImpl();
                user = userDao.queryUserOne(user);
                if (user != null) {
                    message.setMesType(MessageType.message_succeed);
                    oos.writeObject(message);
                    //这里就单开一个线程，让该线程与该客户端保持通讯.
                    SerConClientThread scct = new SerConClientThread(socket);
                    ManageClientThread.addClientThread(user.getNo(), scct);
                    //启动与该客户端通信的线程.
                    scct.start();
                } else {
                    message.setMesType(MessageType.message_login_fail);
                    oos.writeObject(message);
                    //关闭Socket
                    socket.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void shutdown() {
        if (null != serverSocket) {
            try {
                serverSocket.close();
                thread = null;
                System.out.println("服务器停止监听8888端口");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
